package com.mq.batch.consumer1;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.batch.SimpleBatchingStrategy;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.BatchingRabbitTemplate;
import org.springframework.boot.autoconfigure.amqp.SimpleRabbitListenerContainerFactoryConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;

/**
 * 配置
 * @author ytj
 * @date 2024/1/15
 */
@Configuration
public class Demo5Config {

    @Bean
    public Queue demo5Queue(){
        return new Queue(Demo5Message.QUEUE_NAME,true,false,false);
    }

    @Bean
    public Exchange demo5Exchange(){
        return new DirectExchange(Demo5Message.EXCHANGE_NAME,true,false);
    }

    @Bean
    public Binding demo5Binding(){
        return BindingBuilder.bind(demo5Queue()).to(demo5Exchange()).with(Demo5Message.ROUTE_KEY).noargs();
    }

    @Bean
    public BatchingRabbitTemplate demo5BatchingRabbitTemplate(ConnectionFactory connectionFactory){
        //发送消息最大条数
        int batchSize = 16384;
        //发送消息最大内存
        int bufferLimit=33554432;
        //最大等待时间
        int timeout=30000;
        SimpleBatchingStrategy simpleBatchingStrategy = new SimpleBatchingStrategy(batchSize, bufferLimit, timeout);
        //创建taskScheduler，实现超时发送定时器
        TaskScheduler taskScheduler=new ConcurrentTaskScheduler();
        //创建batchingRabbitTemplate对象
        BatchingRabbitTemplate batchingRabbitTemplate = new BatchingRabbitTemplate(simpleBatchingStrategy, taskScheduler);
        batchingRabbitTemplate.setConnectionFactory(connectionFactory);
        return batchingRabbitTemplate;
    }

//    @Bean(name = "consumerBatchContainerFactory")
    public SimpleRabbitListenerContainerFactory consumerBatchContainerFactory(SimpleRabbitListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory){
        //创建simpleRabbitListenerContainerFactory对象
        SimpleRabbitListenerContainerFactory simpleRabbitListenerContainerFactory=new SimpleRabbitListenerContainerFactory();
        configurer.configure(simpleRabbitListenerContainerFactory,connectionFactory);
        //添加批量消费属性
        simpleRabbitListenerContainerFactory.setBatchListener(true);
        return simpleRabbitListenerContainerFactory;
    }
}
